/**
 * API日志中间件
 */

import type { Context } from 'elysia';
import { Logger } from '../utils/response';

/**
 * API访问日志中间件
 */
export function apiLoggerMiddleware() {
  return (app: any) => app
    .onRequest(({ request, set }: Context) => {
      // 记录请求开始时间
      (request as any).startTime = Date.now();
    })
    .onAfterHandle(({ request, set }: Context) => {
      const startTime = (request as any).startTime;
      const duration = startTime ? Date.now() - startTime : 0;
      const method = request.method;
      const url = new URL(request.url);
      const path = url.pathname;
      const statusCode = set.status || 200;
      
      // 记录API访问日志
      Logger.api(method, path, statusCode, duration);
    })
    .onError(({ request, error, set }: Context) => {
      const startTime = (request as any).startTime;
      const duration = startTime ? Date.now() - startTime : 0;
      const method = request.method;
      const url = new URL(request.url);
      const path = url.pathname;
      const statusCode = set.status || 500;
      
      // 记录错误日志
      Logger.error(`${method} ${path} - ${statusCode} | ${duration}ms`, {
        error: error.message,
        stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
      });
    });
}

/**
 * 数据库操作日志
 */
export function logDatabaseOperation(
  operation: string,
  table: string,
  count?: number,
  duration?: number
): void {
  const countStr = count !== undefined ? ` | ${count} records` : '';
  const durationStr = duration !== undefined ? ` | ${duration}ms` : '';
  Logger.info(`DB ${operation.toUpperCase()} ${table}${countStr}${durationStr}`);
}

/**
 * 用户操作日志
 */
export function logUserOperation(
  userId: string,
  username: string,
  operation: string,
  resource?: string,
  details?: any
): void {
  const resourceStr = resource ? ` ${resource}` : '';
  Logger.info(`User ${username}(${userId}) ${operation}${resourceStr}`, details);
}

/**
 * 系统事件日志
 */
export function logSystemEvent(
  event: string,
  details?: any
): void {
  Logger.info(`System Event: ${event}`, details);
}